package com.jams.goodox.activity.mine.settings;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hangzhou.jin.customview.TextMoreLayout;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.login.ResetPwdActivity;
import com.jams.goodox.activity.qa.BannerDetailActivity;
import com.jams.goodox.entity.UserNoticeSet;
import com.jams.goodox.listen.SuccessListener;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TipAlertDialog;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.update.UpDateVersionUtils;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.utils.permission.WriteExternalStorageUtils;
import com.jams.goodox.widget.DataCleanManager;
import com.jams.library.widget.switch_button.SwitchButton;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by Jin on 2016/5/14.
 * Description 系统设置
 */
public class MineSettingsActivity extends BaseActivity {

    @Bind(R.id.rl1)
    RelativeLayout rl1;
    @Bind(R.id.switchBtn)
    SwitchButton switchBtn;
    @Bind(R.id.mTextMoreLayout3)
    TextMoreLayout mTextMoreLayout3;
    @Bind(R.id.mTextMoreLayout4)
    TextMoreLayout mTextMoreLayout4;

    @Bind(R.id.mTextMoreLayout1)
    TextMoreLayout mTextMoreLayout1;

    private Activity activity;

    @Override
    protected int getLayoutId() {
        return R.layout.mine_settings;
    }

    @Override
    protected void init() {
        activity = this;
        StyleUtil.titleBackKey(this, "设置");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部

        rl1.setVisibility(View.VISIBLE);
//        initNotice();

        try {
            mTextMoreLayout3.setRightText(DataCleanManager.getCustomCacheSize(activity));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            mTextMoreLayout4.setRightText("当前版本：" + getVersionName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        NotificationManagerCompat manager = NotificationManagerCompat.from(this);
//        boolean isOpened = manager.areNotificationsEnabled();
//        if(!isOpened){
//            TipAlertDialog.showTip(this, null, null,
//                    "打开通知权限", new SuccessListener() {
//                        @Override
//                        public void success() {
//                            // 根据isOpened结果，判断是否需要提醒用户跳转AppInfo页面，去打开App通知权限
//                            Intent intent = new Intent();
//                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                            Uri uri = Uri.fromParts("package",
//                                    getPackageName(), null);
//                            intent.setData(uri);
//                            startActivity(intent);
//                        }
//                    });
//
//        }else {
//            switchBtn.setChecked(true);
//        }
    }

    private String getVersionName() throws Exception {
        // 获取package manager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

    private void initNotice() {
        enqueue(createCallService(MineService.class).getUserNoticeSet(), new RetrofitCallbackListener<UserNoticeSet>() {
            @Override
            public void onSuccess(Call<UserNoticeSet> call, UserNoticeSet result) {
                UserNoticeSet.DataBean bean = result.getData();
                if (null != bean.getIsAccept())
                    switchBtn.setChecked(bean.getIsAccept().equalsIgnoreCase("1"));
            }

            @Override
            public void onError(String msg) {
                //ToastUtil.show(msg);
            }
        });

        switchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                enqueue(createCallService(MineService.class).userNoticeSet(isChecked ? "1" : "0"), new RetrofitCallbackListener<BaseEntity>() {
                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                    }

                    @Override
                    public void onError(String msg) {
                        //ToastUtil.show(msg);
                    }
                });
            }
        });
    }

    @OnClick({R.id.rl1, R.id.exit,R.id.anquan, R.id.mTextMoreLayout5, R.id.mTextMoreLayout6, R.id.mTextMoreLayout3, R.id.mTextMoreLayout4,R.id.mTextMoreLayout1})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl1:
                NotificationManagerCompat manager = NotificationManagerCompat.from(this);
                boolean isOpened = manager.areNotificationsEnabled();
                if(!isOpened){
                    TipAlertDialog.showTip(this, null, null,
                            "打开通知权限", new SuccessListener() {
                                @Override
                                public void success() {
                                    // 根据isOpened结果，判断是否需要提醒用户跳转AppInfo页面，去打开App通知权限
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package",
                                            getPackageName(), null);
                                    intent.setData(uri);
                                    startActivity(intent);
                                }
                            });

                }
                break;

            case R.id.mTextMoreLayout1:
                qStartActivity(BannerDetailActivity.class);
                break;

            case R.id.mTextMoreLayout2:
                //qStartActivity(InviteActivity.class);
                break;
            case R.id.mTextMoreLayout6:
                qStartActivity(MineFeedback.class);
                break;
            case R.id.exit:
                TipAlertDialog.showTip(mContext, null, null, "您确定退出登录吗？", new SuccessListener() {
                    @Override
                    public void success() {
                        SePref.putToken("");
                        SePref.setId(-1);
                        SePref.setMemberType(1);
                        Utils.logOut(mContext);
                    }
                });
                break;
            case R.id.anquan:
                Log.d("TTTTT","-------888888888-----");
                startActivity(new Intent(this, ResetPwdActivity.class));
                break;
            case R.id.mTextMoreLayout3:
                d1 = showDialogBlack(activity, "清理中...");
                d1.setCancelable(false);
                new MyThread(1).start();
                break;
            case R.id.mTextMoreLayout4:
                new WriteExternalStorageUtils(this).checkExternalPermission(new SuccessListener() {
                    @Override
                    public void success() {
                        UpDateVersionUtils.checkAppVersion(MineSettingsActivity.this, true);
                    }
                });
                break;
        }
    }

    private Dialog d1, d2;

    class MyThread extends Thread {

        int type;

        public MyThread(int type) {
            this.type = type;
        }

        @Override
        public void run() {
            super.run();

            try {
                Thread.sleep(800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (type == 1) {
                DataCleanManager.cleanCustomPathData(activity);
            }

            handler.sendEmptyMessage(type);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 1) {
                d1.dismiss();
                d2 = showDialogBlack(activity, "已成功清理缓存");

                try {
                    mTextMoreLayout3.setRightText("0M");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                new MyThread(2).start();
            } else if (msg.what == 2) {
                d2.dismiss();
            }
        }
    };

    public static Dialog showDialogBlack(Context context, String str) {
        Dialog dialog = new Dialog(context, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(context);
        View v2 = inflater.inflate(R.layout.dialog_black, null);

        Window dw = dialog.getWindow();
        final WindowManager.LayoutParams lp = dw.getAttributes();

        TextView t = (TextView) v2.findViewById(R.id.txt);
        t.setText(str);

        dialog.addContentView(v2, lp);
        dialog.show();
        return dialog;
    }
}
